$(function () {
    var gridColumns = [
        [
            {field:'serialnumber',title:'',width:30},
            {field:'o',title:'操作',width:60,formatter:function () {
                    return gridOpt('#fixtable');
                }},
            {
                field:'productId',
                title:'<span class="red">*</span>商品 -- 扫描枪录入<span init="off" style="position: relative;cursor: pointer;" id="productTitleIcon"></span>',
                width:200,
                editor:'search',
                placeholder:'商品名称、编码、条码',
                searchData:function(that){
                    return $(that).parent().data().product;
                },
                click:datagridSearchClick,
                url:'../../common/product_list.html',
                editBefore:editBefore
            }
        ],
        [
            {field:'storeId',title:'<span class="red">*</span>仓库',width:120,editor:'combobox',editBefore:editBefore,
                getData:function(cell,callback){
                    app.request({
                        url:'store/select',
                        success:function (resp) {
                            callback(resp.data);
                        }
                    });
                },comboboxData:function (that) {
                    return $(that).data();
                }
            },
            {field:'unitId',title:'单位',width:80,editor:'combobox',editBefore:editBefore,
                getData:function(cell,callback){
                    var rowData = cell.parent().data().product;

                    app.request({
                        url:'product/getMultiUnit',
                        data:{productId:rowData.id},
                        success:function (resp) {
                            var comboData = [{id:rowData.unitId,name:rowData.unitName}];
                            comboData.merge(resp.data);
                            callback(comboData);
                        }
                    });
                },comboboxData:function (that) {
                    return $(that).data();
                }
            },
            {field:'price',title:'<span class="red">*</span>单价',width:120,editor:'decimal',editBefore:editBefore,editAfter:autoCalc},
            {field:'number',title:'<span class="red">*</span>数量',width:80,editor:'decimal',editBefore:editBefore,editAfter:autoCalc},
            {field:'batchNo',title:'批次号',width:180,hide:true,align:'right',
                editor:'search',
                placeholder:'批次号',
                searchData:function(that,thatHisHtml){
                    return {id:thatHisHtml,name:thatHisHtml};
                },
                click:batchNoSearchClick,
                editBefore:function (cell) {
                    if(editBefore(cell)){
                        return getRowDataByCell(cell).product.enableBatch == 1;
                    }
                    return false;
                }
            },
            {field:'productionDate',title:'生产日期',width:150,hide:true,editBefore:function (cell) {
                    if(editBefore(cell)){
                        return getRowDataByCell(cell).product.enableFine == 1;
                    }
                    return false;
                },editor:'date'},
            {field:'fineDays',title:'保质天数',width:100,hide:true,align:'right'},
            {field:'discountRate',title:'折扣率%',width:120,editor:'number',editBefore:editBefore,editAfter:autoCalc},
            {field:'discountMoney',title:'折扣额',width:120,editor:'decimal',editBefore:editBefore,editAfter:autoCalc},
            {field:'discountPrice',title:'折后金额',editor:'decimal',width:120,editBefore:editBefore,editAfter:autoCalc},
            {field:'remarks',title:'备注',width:180,editBefore:editBefore,editor:'text'},
            {field:'orgCode',title:'来源订单号',width:180}
        ]
    ];
    $('#fixtable').fixgrid({
        columns:gridColumns
    });

    $('#fixtable').fixgrid('loadData',{bottom:true,rows:[{}]});

    var torderId = params.id , torderType = orderType;

    if( params.ot ){
        torderId = params.orderId;
        torderType = params.ot;
    }
    if( torderId ){
        app.request({
            url:'order/getOrder',
            data:{id:torderId,orderType:torderType},
            success:function(resp){
                init_edit(resp.data);
            }
        });
    }else{
        $('#order_title').html('新增'+orderText+'单');
        createRow();createRow();createRow();createRow();createRow();
    }

    laydate.render({
        elem: '#order_date',value:new Date(app.getServerTime())
    });

    $('input[n="money"]').blur(autoCalcOrder).keyup(function(event){
        if(event.keyCode ==13){
            $(this).blur();
        }
    });
    
    if( orderType >= 20 ){
        $('#relationId').search({
            name:'order.relationId',
            click:function () {
                if( pageEdit ){
                    app.window(layer,{
                        title:'客户选择',
                        btn:[],
                        area: ['860px', '600px'],
                        content: '../../common/customer_list.html?index=-1&queryId=relationId'
                    });
                }
            }
        });
    }else{
        $('#relationId').search({
            name:'order.relationId',
            click:function () {
                if( pageEdit ){
                    app.window(layer,{
                        title:'供应商选择',
                        btn:[],
                        area: ['860px', '600px'],
                        content: '../../common/vendor_list.html?index=-1&queryId=relationId'
                    });
                }
            }
        });
    }

    if( !torderId ){
        if( orderType >= 20 ){
            $('#relationId').search("setValue",top.lastSelectCustomerId,top.lastSelectCustomerName);
        }else{
            $('#relationId').search("setValue",top.lastSelectVendorId,top.lastSelectVendorName);
        }
    }

    $('#fee_set').click(function () {
        if( pageEdit ){
            var title = orderType<20?'采购费用':'销售费用';
            app.window(layer,{
                title:title,
                area: ['700px', '600px'],
                content: '../../common/sesubject_list.html?relationType=1'
            });
        }
    });

    initButtons({service:'order',htmlName:htmlName,orderText:orderText,codePrefix:codePrefix,orderType:orderType});
    initAccount();

});

var backEditFlag = true;
function initBackPaage() {
    if( orderType != 23 && orderType != 4 ){
        return;
    }
    if( params.thType != 2 ){
        return;
    }
    backEditFlag = false;
}

function initAccount() {
    $('#accountId').combobox({
        url:'account/select',emptyRow:true,
        direction:'up',valueField:'id',textField:'name',
        name:'order.accountId',
        data:[{id:-2,name:'多账户'}],
        edit:function(){
            return pageEdit;
        },
        click:function (value,text) {
            if( value==-2 ){
                $('input[name="order.realMoney"]').attr("readonly","readonly");
                app.window(layer,{
                    title:'多账户收款',
                    area: ['500px', '400px'],
                    content: '../../common/account_list.html'
                });
            }else{
                $('input[name="order.realMoney"]').removeAttr("readonly");
            }
        }
    });
}

function init_edit_buttons(order) {
    if(order.status == 1){
        enablePageEdit();
        toSaveBtns();
    }else if(order.status > 1 && !params.ot){
        disablePageEdit();
        app.showExam();
        toExamineBtns(order);
    }
}

function init_edit_params(order) {
    params.code = order.code;
    params.status = order.status;
    params.orderType = orderType;
}

function init_edit_showCol(details,field,columns) {
    for (var i=0 ; i<details.length ; i++){
        if( details[i][field] == 1 ){
            $('#fixtable').fixgrid('showColumns',columns);
            return;
        }
    }
}

function init_edit(data){
    var details = data.details;
    var accounts = data.accounts;
    var order = data.order;
    var orderResubjects = data.orderResubjects;

    if( orderResubjects && orderResubjects.length>0 ){
        window.sesubjects = orderResubjects;
    }
    if( params.orderId ){
        $('#order_title').html('新增'+orderText+'单');
    }else{
        $('#order_title').html('编辑'+orderText+'单 [ '+codePrefix+order.code+' ]');
    }



    init_edit_buttons(order);
    init_edit_params(order);

    if( orderType == 1 || orderType == 20 ){
        $('input[name="order.bussType"][value="'+order.bussType+'"]').prop('checked',true);
    }

    $('#relationId').search('setValue',order.relationId,order.relationName);
    $('#order_date').val(app.time2str(order.date));

    $('input[name="order.remarks"]').val(order.remarks);
    $('input[name="order.dueMoney"]').val(app.div(order.dueMoney,app.DIV));
    $('input[name="order.purPrice"]').val(app.div(order.purPrice,app.DIV));
    $('input[name="order.realMoney"]').val(app.div(order.realMoney,app.DIV));
    $('input[name="order.discountMoney"]').val(app.div(order.discountMoney,app.DIV));
    $('input[name="order.debtMoney"]').val(app.div(order.debtMoney,app.DIV));

    for (var i=0 ; i<details.length ; i++){
        init_edit_detail(details[i],i);
    }

    if( accounts!=null && accounts.length>0 ){
        if( accounts.length==1 ){
            $('#accountId').combobox('setValue',accounts[0].accountId,accounts[0].accountName);
        }else{
            $('#accountId').combobox('setValue',-2,'多账户');
            window.accounts = accounts;
        }
    }
    autoCalc();
    initBackPaage();

    //show columns
    init_edit_showCol(details,'enableBatch',['batchNo']);
    init_edit_showCol(details,'enableFine',['productionDate','fineDays']);
}

function init_edit_detail(product,i) {
    product.id = product.productId;
    product.name = product.productName;
    createRow();
    var leftRow = $('#fixtable .ctx-left .vui-table .vui-table-row').eq(i);
    var rightRow = $('#fixtable .ctx-right .vui-table .vui-table-row').eq(i);
    var searchCell = leftRow.find('.vui-table-cell[field="productId"]');
    searchCell.data({product:product});
    searchCell.html(product.name);
    leftRow.data({product:product});
    rightRow.data({product:product});
    init_edit_detail_column(rightRow,product);
    rightRow.find('.vui-table-cell[field="storeId"]').html(product.storeName).data({value:product.storeId,text:product.storeName});
    rightRow.find('.vui-table-cell[field="unitId"]').html(product.unitName).data({value:product.unitId,text:product.unitName});
    rightRow.find('.vui-table-cell[field="price"]').html(app.div(product.price,app.DIV));
    rightRow.find('.vui-table-cell[field="number"]').html(app.transNumber(app.div(product.number,app.DIV)));
    rightRow.find('.vui-table-cell[field="discountRate"]').html(product.discountRate);
    rightRow.find('.vui-table-cell[field="discountMoney"]').html(app.div(product.discountMoney,app.DIV));
    rightRow.find('.vui-table-cell[field="discountPrice"]').html(app.div(product.discountPrice,app.DIV));
    rightRow.find('.vui-table-cell[field="remarks"]').html(product.remarks);

    rightRow.find('.vui-table-cell[field="batchNo"]').html(product.batchNo);
    rightRow.find('.vui-table-cell[field="productionDate"]').html(app.time2str(product.productionDate));
    if(product.fineDays>0)rightRow.find('.vui-table-cell[field="fineDays"]').html(product.fineDays);



    if(params.orderCode){
        $('#fixtable table[type="body"] tr').eq(i).find('td[field="orgCode"] .cell').html(params.orderCode);
    }
}

function init_edit_detail_column(rightRow,product) {
    if( product.enableBatch ){
        rightRow.find('.vui-table-cell[field="fineDays"]').html(product.fineDays);
    }
    if( product.enableFine ){
        rightRow.find('.vui-table-cell[field="batchNumber"]').html(product.batchNumber);
        rightRow.find('.vui-table-cell[field="makeDate"]').html(product.makeDate);
    }
}

//保存
var accounts = [],oldAccounts = [],sesubjects=[];
function saveAction(saveType,obj){
    var data = app.serializeForm();
    data.saveType = saveType;
    data['order.date'] =new Date(data['order.date']).getTime();
    data['order.orderType'] = orderType;

    //account
    var accountId = $('input[name="order.accountId"]').val();
    if( parseInt($.trim(accountId)) > 0 ){
        accounts = [{accountId:accountId,amount:data['order.dueMoney']}];
    }

    if( accounts.length > 0 ){
        $.each(accounts,function (i,row) {
            data["accounts["+i+"].accountId"] = row.accountId;
            data["accounts["+i+"].amount"] = parseInt(row.amount);
        });
    }

    if( sesubjects.length > 0 ){
        $.each(sesubjects,function (i,row) {
            data["resubjects["+i+"].resubjectId"] = row.resubjectId;
            data["resubjects["+i+"].amount"] = parseInt(row.amount);
            data["resubjects["+i+"].remarks"] = row.remarks;
        });
    }

    $.each(details,function(i,row){
        for ( var n in row ){
            data["details["+i+"]."+n] = row[n];
        }
        data["details["+i+"].ord"] = i;
    });

    var url = 'order/insert';

    if(params.id){
        data['order.id'] = params.id;
        url = 'order/update';
    }

    if(params.orderId){
        data['order.orderId'] = params.orderId;
        data['order.thType'] = params.thType;
        data['order.orderCode'] = params.orderCode;
    }else{
        data['order.thType'] = 0;
    }
    doSave(url,data,saveType,obj);
}

function checkAccountIn() {
    var orderRealMoney = $('input[name="order.realMoney"]').val();
    if( orderRealMoney.length > 0 && orderRealMoney > 0 ){
        var orderAccountId = $('input[name="order.accountId"]').val();
        if( orderAccountId==null || orderAccountId==undefined || $.trim(orderAccountId).length==0 ){
            app.msg(layer,'填写收款金额必须选择结算账户',2);
            checkRowsTip = true;
            return false;
        }
    }
    return true;
}

var checkRowsTip = false;
function checkRows() {
    details = [];
    $('#fixtable .ctx-left .vui-table-row').each(function () {
        var product = getRowEleProduct($(this));
        if( product && product.id ){
            var n = $(this).attr('i');
            //body区域对应行
            var bodyTr = $('#fixtable .ctx-right .vui-table-row').eq(n);

            var buyCheckResult = buyCheck(bodyTr,product);
            if(buyCheckResult){
                var detail = {productId:product.id,enableBatch:product.enableBatch,enableFine:product.enableFine};
                if( typeof(buyCheckResult) == 'object'  ){
                    detail.batchNo = buyCheckResult.batchNo;
                    detail.productionDate = buyCheckResult.productionDate;
                }
                //仓库
                var stone = getField(bodyTr,'storeId').data();
                if( !stone.value ){
                    app.msg(layer,'商品【'+product.name+'】未选择仓库',2);
                    checkRowsTip = true;
                    return false;
                }
                detail.storeId = stone.value;detail.companyId = stone.companyId;
                // 单位
                var unitNameData = getField(bodyTr,'unitId').data();
                detail.unitId = unitNameData.value;
                detail.unitMain = unitNameData.main ? 1 : 0;
                // 单价
                detail.price = app.mul(getField(bodyTr,'price').html(),app.DIV,0);
                // 数量
                detail.number = app.mul(getField(bodyTr,'number').html(),app.DIV,0);
                // 折扣率%
                detail.discountRate = getField(bodyTr,'discountRate').html();
                // 折扣额
                detail.discountMoney = app.mul(getField(bodyTr,'discountMoney').html(),app.DIV,0);
                // 折后金额
                detail.discountPrice = app.mul(getField(bodyTr,'discountPrice').html(),app.DIV,0);
                // 备注
                detail.remarks = getField(bodyTr,'remarks').html();

                if( params.ot ){
                    detail.orderDetailId = product.orderDetailId;
                }

                details.push(detail);
            }
        }
    });
}

function buyCheck(bodyEle,product) {
    if( orderType == 1 || orderType == 20 ){
        return true;
    }
    // 3 4 22 23


    if( product.enableBatch == 1 || product.enableFine == 1 ){
        var o = {};
        if( product.enableBatch == 1 ){
            var batchNo = $.trim(getField(bodyEle,'batchNo').html());
            if(batchNo.length==0 ){
                app.msg(layer,'商品【'+product.name+'】批次号未录入',2);
                checkRowsTip = true;
                return false;
            }
            o.batchNo = batchNo;
        }
        if( product.enableFine == 1 && orderType == 3 ){
            var productionDate = $.trim(getField(bodyEle,'productionDate').html());
            if(productionDate.length==0 ){
                app.msg(layer,'商品【'+product.name+'】生产日期未录入',2);
                checkRowsTip = true;
                return false;
            }
            o.productionDate = new Date(productionDate).getTime();
        }
        return o;
    }

    return true;
}

//表单检查
var details = [];
function checkForm(){
    checkRowsTip = false;
    var checkOptions = [
        {type:'input',name:'order.relationId_text',verify:[{type:'required'}]},
        {type:'input',name:'order.date',verify:[{type:'required'}]}
    ];
    if(app.checkForm(checkOptions)){
        if(!checkAccountIn()){
            return false;
        }
        checkRows();
        if(checkRowsTip)return false;
        if(details.length == 0){
            app.msg(layer,'至少填写一条商品记录',2);
            return false;
        }else{
            return true;
        }
    }
    return false;
}

// button action end

function productSelected(cell) {

    var obj = productSelectedCommon(cell);
    var product = obj.product;
    var rightRow = obj.rightRow;
    setStore(obj.rightRow);

    if( app.getDictValue(2000000005) == 1 && product.enableBatch == 1  &&  orderType!=1 && orderType!=20  ){
        $('#fixtable').fixgrid('showColumns',['batchNo']);
    }

    if( app.getDictValue(2000000004) == 1 && product.enableFine == 1 && orderType == 3 ){
        $('#fixtable').fixgrid('showColumns',['productionDate','fineDays']);
    }

    if(product.fineDays>0)rightRow.find('.vui-table-cell[field="fineDays"]').html(product.fineDays);

    rightRow.find('.vui-table-cell[field="unitId"]').html(product.unitName).data({value:product.unitId,text:product.unitName});
    var price = 0;
    if( orderType < 20 ){
        price = product.lastPurchasePrice > 0 ? product.lastPurchasePrice : product.purchasePrice;
    }else{
        price = product.lastSalePrice > 0 ? product.lastSalePrice : product.salePrice;
    }

    rightRow.find('.vui-table-cell[field="price"]').html(app.div(price,app.DIV));
    rightRow.find('.vui-table-cell[field="number"]').html(1);
    rightRow.find('.vui-table-cell[field="discountRate"]').html(100);
    rightRow.find('.vui-table-cell[field="discountMoney"]').html(0);
    rightRow.find('.vui-table-cell[field="discountPrice"]').html(app.div(price,app.DIV));
    rightRow.find('.vui-table-cell[field="remarks"]').html(product.remarks);
    autoCalc();
}

var defaultStone = null;
function setStore(rightRow) {
    if( defaultStone == null ){
        app.request({
            url:'store/getDefault',
            success:function(resp){
                defaultStone = resp.data;
                setStoreLocal(rightRow);
            }
        });
    }else{
        setStoreLocal(rightRow);
    }
}

function setStoreLocal(rightRow) {
    rightRow.find('.vui-table-cell[field="storeId"]').html(defaultStone.name).data({value:defaultStone.id,text:defaultStone.name});
}



function autoCalc(cell) {
    if(cell){
        autoCalcRow(cell);
    }

    var nums = 0,discountMoneys=0,discountPrices=0;

    $('#fixtable .ctx-right .vui-table .vui-table-row').each(function () {
        if( $(this).attr('bottom') == '1' )return;
        var eles = getChangeEles($(this));
        nums = app.add(eles.number.html(),nums);
        discountMoneys = app.add(eles.discountMoney.html(),discountMoneys);
        discountPrices = app.add(eles.discountPrice.html(),discountPrices);
    });

    var bottomRow = $('#fixtable .vui-table-row[bottom="1"]');
    bottomRow.find('.vui-table-cell[field="number"]').html((parseFloat(nums)+'').replace('.00',''));
    bottomRow.find('.vui-table-cell[field="discountMoney"]').html(discountMoneys);
    bottomRow.find('.vui-table-cell[field="discountPrice"]').html(discountPrices);

    $('input[name="order.dueMoney"]').val(discountPrices);
    autoCalcOrder();
}

function getChangeEles(row) {
    var ele = {};
    //单价
    ele.price = row.find('.vui-table-cell[field="price"]');
    //数量
    ele.number = row.find('.vui-table-cell[field="number"]');
    //折扣率
    ele.discountRate = row.find('.vui-table-cell[field="discountRate"]');
    //折扣额
    ele.discountMoney = row.find('.vui-table-cell[field="discountMoney"]');
    //折后金额
    ele.discountPrice = row.find('.vui-table-cell[field="discountPrice"]');
    return ele;
}

function autoCalcRow(cell){
    var row = cell.parent();
    var eles = getChangeEles(row);
    //单价
    var price = eles.price.html();
    //数量
    var number = eles.number.html();
    //折扣率
    var discountRate = eles.discountRate.html();
    //折扣额
    var discountMoney = eles.discountMoney.html();
    //折后金额
    var discountPrice = eles.discountPrice.html();

    var field = cell.attr('field');
    var money = app.mul(price,number);
    if(field=='discountMoney'){
        var dp = app.sub(money,discountMoney);
        var dr = app.div(dp,money)*100; //  此处100非app.DIV
        eles.discountPrice.html(dp);
        eles.discountRate.html(dr);
    }else if(field=='discountPrice'){
        var dm = app.sub(money,discountPrice);
        var dr = app.div(discountPrice,money)*100; //  此处100非app.DIV
        eles.discountMoney.html(dm);
        eles.discountRate.html(dr);
    }else{
        var dp = app.div(app.mul(money,discountRate),100); //  此处100非app.DIV
        var dm = app.sub(money,dp);
        eles.discountPrice.html(dp);
        eles.discountMoney.html(dm);
    }
}

function autoCalcOrder() {
    //订单金额      订单金额是未优惠前的金额 不允许修改此逻辑
    var dueMoney = $('input[name="order.dueMoney"]').val();
    //本次付款
    var realMoney = $('input[name="order.realMoney"]').val();
    //折让金额
    var discountMoney = $('input[name="order.discountMoney"]').val();

    //本次欠款
    $('input[name="order.debtMoney"]').val(app.sub(app.sub(dueMoney,realMoney),discountMoney));
}